using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace Sensor.UI.Utils;

/// <summary>
/// 高速数据处理器，专为低延迟场景设计
/// </summary>
public class HighSpeedDataProcessor : IDisposable
{
    private readonly RingBuffer<byte[]> _buffer;
    private readonly SemaphoreSlim _processingLock = new(1, 1);
    private readonly CancellationTokenSource _cancellationTokenSource = new();
    private readonly object _uiUpdateLock = new();
    private bool _isProcessing = false;
    private bool _disposedValue = false;
    
    // UI更新相关
    private readonly Queue<string> _uiUpdateQueue = new();
    private DateTime _lastUIUpdate = DateTime.MinValue;
    private readonly TimeSpan _uiUpdateInterval = TimeSpan.FromMilliseconds(16); // 约60FPS
    
    // 事件
    public event Action<string>? OnDataReady;
    
    // 性能计数器
    private long _processedCount = 0;
    private long _droppedCount = 0;
    
    public long ProcessedCount => _processedCount;
    public long DroppedCount => _droppedCount;
    public int QueueCount => _buffer.Count;
    
    public HighSpeedDataProcessor(int bufferCapacity = 10000)
    {
        _buffer = new RingBuffer<byte[]>(bufferCapacity);
        
        // 启动后台处理任务
        Task.Run(ProcessDataAsync, _cancellationTokenSource.Token);
    }
    
    /// <summary>
    /// 添加数据到处理器
    /// </summary>
    /// <param name="data">要处理的字节数据</param>
    public void AddData(byte[] data)
    {
        if (_disposedValue || data == null || data.Length == 0)
            return;
            
        // 尝试添加到缓冲区
        bool overwritten = _buffer.TryAdd(data);
        if (overwritten)
        {
            Interlocked.Increment(ref _droppedCount);
        }
        
        // 触发处理（如果尚未处理）
        TriggerProcessing();
    }
    
    /// <summary>
    /// 触发数据处理
    /// </summary>
    private void TriggerProcessing()
    {
        if (_isProcessing)
            return;
            
        if (_processingLock.Wait(0)) // 非阻塞获取锁
        {
            try
            {
                _isProcessing = true;
                Task.Run(() => ProcessBufferAsync(), _cancellationTokenSource.Token);
            }
            finally
            {
                _processingLock.Release();
            }
        }
    }
    
    /// <summary>
    /// 后台持续处理数据
    /// </summary>
    private async Task ProcessDataAsync()
    {
        while (!_cancellationTokenSource.Token.IsCancellationRequested)
        {
            await Task.Delay(1, _cancellationTokenSource.Token); // 最小延迟
            
            if (_buffer.Count > 0)
            {
                TriggerProcessing();
            }
        }
    }
    
    /// <summary>
    /// 处理缓冲区中的数据
    /// </summary>
    private async Task ProcessBufferAsync()
    {
        var items = new byte[100][]; // 批量处理大小
        
        try
        {
            while (_buffer.TryTakeRange(items, out int count) && count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    if (_cancellationTokenSource.Token.IsCancellationRequested)
                        break;
                        
                    ProcessItem(items[i]);
                    Interlocked.Increment(ref _processedCount);
                }
                
                // 短暂让出CPU，避免长时间占用
                if (count == items.Length)
                {
                    await Task.Yield();
                }
            }
        }
        finally
        {
            _isProcessing = false;
        }
    }
    
    /// <summary>
    /// 处理单个数据项
    /// </summary>
    private void ProcessItem(byte[] item)
    {
        // 将字节数据转换为字符串
        string dataString = Encoding.UTF8.GetString(item);
        
        lock (_uiUpdateLock)
        {
            _uiUpdateQueue.Enqueue(dataString);
            
            // 检查是否需要更新UI
            var now = DateTime.UtcNow;
            if (now - _lastUIUpdate >= _uiUpdateInterval || _uiUpdateQueue.Count >= 50)
            {
                _lastUIUpdate = now;
                ScheduleUIUpdate();
            }
        }
    }
    
    /// <summary>
    /// 调度UI更新
    /// </summary>
    private void ScheduleUIUpdate()
    {
        // 复制队列中的数据以避免长时间锁定
        string[] itemsToUpdate;
        lock (_uiUpdateLock)
        {
            itemsToUpdate = _uiUpdateQueue.ToArray();
            _uiUpdateQueue.Clear();
        }
        
        if (itemsToUpdate.Length == 0)
            return;
            
        // 使用BeginInvoke进行异步UI更新，避免阻塞
        if (Application.Current?.Dispatcher != null)
        {
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
            {
                try
                {
                    // 合并所有数据为一个字符串
                    var combinedData = string.Join(Environment.NewLine, itemsToUpdate);
                    OnDataReady?.Invoke(combinedData);
                }
                catch (Exception ex)
                {
                    // 记录错误但不中断处理
                    System.Diagnostics.Debug.WriteLine($"UI更新错误: {ex.Message}");
                }
            }));
        }
    }
    
    /// <summary>
    /// 强制立即更新UI
    /// </summary>
    public void FlushUI()
    {
        lock (_uiUpdateLock)
        {
            if (_uiUpdateQueue.Count > 0)
            {
                _lastUIUpdate = DateTime.MinValue; // 强制更新
                ScheduleUIUpdate();
            }
        }
    }
    
    #region IDisposable实现
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposedValue)
        {
            if (disposing)
            {
                _cancellationTokenSource.Cancel();
                _processingLock.Dispose();
                _buffer.Clear();
            }
            _disposedValue = true;
        }
    }
    
    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }
    #endregion
}